//
//  BleViewController.m
//  bleDemo
//
//  Created by wurz on 15/4/14.
//  Copyright (c) 2015年 wurz. All rights reserved.
//

#import "BleViewController.h"
#import "BleSendReceiveTableViewCell.h"
#import "WiseWaitEvent.h"

@interface BleViewController ()
{
    DXMessageToolBar *_chatToolBar;
    UITableView *_tableView;
    
    NSMutableArray *_tableData;
    
    UIBarButtonItem *_startBt;
    UIBarButtonItem *_stopBt;
    UIBarButtonItem *_clearBt;
    
    bool _isSendBt;
    
    bool _isLoop;
    
    WiseWaitEvent *_sendEvent;
    
    BluetoothLe *_ble;
}

@end

@implementation BleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.edgesForExtendedLayout = UIRectEdgeNone;
//    
//    self.extendedLayoutIncludesOpaqueBars = NO;
//    self.modalPresentationCapturesStatusBarAppearance = NO;
    
    self.navigationItem.title = @"0";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _startBt = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(start)];
    _stopBt = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(stop)];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    //解决定义按钮与边框距离过大问题
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    spaceItem.width = -12;
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarItem];
    
    _clearBt = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(clearData)];
    self.navigationItem.rightBarButtonItems = @[_clearBt,_startBt];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-[DXMessageToolBar defaultHeight]) style:UITableViewStylePlain];
    //去除多余的分割线
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight], self.view.frame.size.width, [DXMessageToolBar defaultHeight])];
    _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
    _chatToolBar.delegate = self;
    
    [self.view addSubview:_chatToolBar];
    
    _isSendBt = YES;
    _isLoop = NO;
    _sendEvent = [[WiseWaitEvent alloc] init];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardHidden)];
    [self.view addGestureRecognizer:tap];
    
    _tableData = [[NSMutableArray alloc] init];
    
    _ble = [BluetoothLe shareBandConnectionWithDelegate:self];
    _ble.delegate = self;
}

-(void)back
{
    _isLoop = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)clearData
{
    _tableData  = [NSMutableArray array];
    self.title = @"0";
    
    [_tableView reloadData];
}

- (void)start
{
    _chatToolBar.userInteractionEnabled = NO;
    _clearBt.enabled = NO;
    self.navigationItem.rightBarButtonItems = @[_clearBt,_stopBt];
    _isSendBt = NO;
    
    _isLoop = YES;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        while (_isLoop) {
            [self sendData:@"5555555555555555555555555555555555555555"];
//            usleep(40000); //40ms
        }
    });
}


- (void)stop
{
    _chatToolBar.userInteractionEnabled = YES;
    _clearBt.enabled = YES;
    self.navigationItem.rightBarButtonItems = @[_clearBt,_startBt];
    _isSendBt = YES;
    _isLoop = NO;
}

- (void)sendData:(NSString *)text
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    NSDate* now = [NSDate date];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    fmt.dateFormat = @"HH:mm:ss";
    NSString* dateString = [NSString stringWithFormat:@"时间:%@",[fmt stringFromDate:now]];
    [dict setValue:dateString forKey:@"time"];
    [dict setValue:@"发送:" forKey:@"title"];
    [dict setValue:text forKey:@"context"];
    
    [_tableData addObject:[BleSendReceiveData BleSendReceiveDataWithDictionary:dict]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_tableData.count > 50) {
            [_tableData removeObjectAtIndex:0];
        }
        [_tableView reloadData];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_tableData.count-1 inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        [_sendEvent waitOver:WaitResultSuccess];
    });
    
    [_sendEvent waitSignle:500];

    
    //发送数据
    [_ble write:_peripheral value:[NSData stringToHex:text]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableData.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"myCell";
    BleSendReceiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[BleSendReceiveTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    cell.bleData = _tableData[indexPath.row];
    //cell.backgroundColor = [UIColor clearColor];
    return cell;
}

#pragma mark -- UITableViewDelegete
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BleSendReceiveTableViewCell * cell = [[BleSendReceiveTableViewCell alloc]init];
    cell.bleData = _tableData[indexPath.row];
    
    return cell.height;
}

- (void)keyBoardHidden
{
    [_chatToolBar endEditing:YES];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark - DXMessageToolBarDelegate
- (void)inputTextViewWillBeginEditing:(XHMessageTextView *)messageInputTextView{
}

- (void)didChangeFrameToHeight:(CGFloat)toHeight
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = _tableView.frame;
        rect.size.height = self.view.frame.size.height - toHeight;
        _tableView.frame = rect;
    }];
}

- (void)toolBar:(DXMessageToolBar *)toolBar didSendText:(NSString *)text
{
    if (!text || text.length <= 0) {
        return ;
    }
    if (text.length%2) {
        [MBProgressHUD showError:@"数据不为2的倍数" toView:self.view duration:1.0];
        return ;
    }
    
    [self sendData:text];
    
    [toolBar clearText]; //清空发送的数据
}

#pragma mark -- BluetoothLeDegelete
-(void)ble:(BluetoothLe *)ble didLocalState:(BleLocalState)state
{
    if (state != BleLocalStatePowerOn) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        if ([self.delegate respondsToSelector:@selector(handleBleViewShowMessage:)]) {
            [self.delegate handleBleViewShowMessage:@"蓝牙已关闭"];
        }
    }
}

-(void)ble:(BluetoothLe *)ble didDisconnect:(CBPeripheral *)peripheral
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    if ([self.delegate respondsToSelector:@selector(handleBleViewShowMessage:)]) {
        [self.delegate handleBleViewShowMessage:@"蓝牙已断开"];
    }
}

-(void)ble:(BluetoothLe *)ble didWriteData:(CBPeripheral *)peripheral result:(BOOL)bResult
{
    if (bResult) {
        self.title = [NSString stringWithFormat:@"%lld",[self.title longLongValue]+1];
        
        if (!_isLoop) {
            [MBProgressHUD showSuccess:@"发送成功" toView:self.view duration:1.0];
        }
//        [_sendEvent waitOver:WaitResultSuccess];
    }
    else{
        [MBProgressHUD showError:@"发送失败" toView:self.view duration:1.0];
//        [_sendEvent waitOver:WaitResultFailed];
    }
}

-(void)ble:(BluetoothLe *)ble didReceiveData:(CBPeripheral *)peripheral data:(NSData *)data
{
    if (_isLoop) {
        return ;
    }
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    NSDate* now = [NSDate date];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    fmt.dateFormat = @"HH:mm:ss";
    NSString* dateString = [NSString stringWithFormat:@"时间:%@",[fmt stringFromDate:now]];
    [dict setValue:dateString forKey:@"time"];
    [dict setValue:@"接收:" forKey:@"title"];
    [dict setValue:[NSString hexToString:data space:NO] forKey:@"context"];
    
    [_tableData addObject:[BleSendReceiveData BleSendReceiveDataWithDictionary:dict]];
    [_tableView reloadData];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_tableData.count-1 inSection:0];
    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
